<template>
  <div class="user-profile">
    <div class="profile-content">
      <div class="logo-container">
        <img :src="userData.vipImg || '@/assets/images/logo_icon.png'" alt="Avatar" class="logo">
      </div>
      
      <div class="info-table">
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_username') }} </div>
          <div class="info-value" @click="showNicknamePopup">
            {{ userData.nikename || 'EstelarOlas' }}
            <van-icon name="edit" class="edit-icon" />
          </div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_account') }}</div>
          <div class="info-value">+{{ userData.areacode }} {{ userData.tel }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_id') }}</div>
          <div class="info-value">{{ userData.member }}</div>
        </div>
        <!-- <div class="info-row">
          <div class="info-label">E-mail:</div>
          <div class="info-value" v-if="userData.email">{{ userData.email }}</div>
          <div class="info-value link" v-else @click="linkEmail">Link Google Account</div>
        </div> -->
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_vipLevel') }}</div>
          <div class="info-value">{{ userData.minlevel || 1 }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_inviteCode') }}</div>
          <div class="info-value">{{ userData.recomcode || '-' }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('profile_walletDeposit') }}:</div>
          <div class="info-value">COP {{ formatNumber(userData.inusable || 0) }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('profile_walletIncome') }}:</div>
          <div class="info-value">COP {{ formatNumber(userData.yuusable || 0) }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_totalIncome') }}</div>
          <div class="info-value">COP {{ formatNumber(userData.totalIncome || 0) }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ t('userprofile_appVersion') }}</div>
          <div class="info-value">2.1.22</div>
        </div>
      </div>
    </div>
    
    <!-- 昵称修改弹窗 -->
    <van-popup v-model:show="showPopup" position="bottom" round>
      <div class="popup-content">
        <div class="popup-title">{{ t('userprofile_editTitle') }}</div>
        <van-field
          v-model="newNickname"
          :placeholder="t('userprofile_inputPlaceholder')"
          maxlength="20"
          class="nickname-input"
        />
        <div class="popup-buttons">
          <van-button round block :loading="isSubmitting" @click="updateNickname" class="confirm-button">
            {{ t('userprofile_confirm') }}
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
// 导入所需的依赖
import { editNickname, getUserInfo } from '@/api/user';
import { formatNumber } from '@/utils/public';
import { Button as VanButton, Field as VanField, Icon as VanIcon, Popup as VanPopup, closeToast } from 'vant';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
const { t } = useI18n();
// 定义API响应类型
interface ApiResponse {
  code: number
  msg?: string
  data?: any
}


// 定义用户数据接口
interface UserData {
  tradpasswordstate?: string
  todayPromotionIncome?: string
  headimg?: string
  vipImg?: string
  yuusable?: string
  nikename?: string
  rewardstate?: string
  recomcode?: string
  todayTeamIncome?: string
  areacode?: string
  inusable?: string
  totalIncome?: string
  idcard?: string
  minlevel?: string
  member?: string
  tel?: string
  idcardstate?: string
  recomurl?: string
  email?: string
}

// 初始化数据
const router = useRouter()
const userData = reactive<UserData>({})
const isLoading = ref(false)
const isSubmitting = ref(false)

// 昵称编辑相关
const showPopup = ref(false)
const newNickname = ref('')

// 显示昵称修改弹窗
function showNicknamePopup() {
  newNickname.value = userData.nikename || '' // 设置默认值为当前昵称
  showPopup.value = true
}

// 修改昵称
async function updateNickname() {
  if (!newNickname.value.trim()) {
    showToast(t('userprofile_emptyTip'))
    return
  }
  
  if (isSubmitting.value) return
  isSubmitting.value = true
  
  try {
    showToast({
      type:'loading',
      message: t('userprofile_updating'),
      forbidClick: true,
      duration: 0
    })
    
    // 调用API修改昵称
    const result = await editNickname(newNickname.value)
    const response = result as unknown as ApiResponse
    
    closeToast() // 关闭loading提示
    
    if (response && (response.code === 0 || response.code === 200)) {
      // 成功
      userData.nikename = newNickname.value
      showToast({
        type: 'success',
        message:  t('userprofile_updateSuccess'),
      })
      showPopup.value = false
    } else {
      // 失败
      showToast({
        type: 'fail',
        message: response?.msg || t('userprofile_updateFail'),
      })
    }
  } catch (error: any) {
    closeToast() // 关闭loading提示
    console.error('err:', error)
    showToast({
      type: 'fail',
      message: error?.message || t('userprofile_updateFail'),
    })
  } finally {
    isSubmitting.value = false
  }
}

// 链接邮箱账号
function linkEmail() {
  // 链接邮箱账号逻辑
  // showToast('Fungsi ini sedang dikembangkan')
    showToast(t('userprofile_devTip'))
}



// 获取用户信息
async function fetchUserInfo() {
  if (isLoading.value) return
  isLoading.value = true
  
  try {
    const result = await getUserInfo()
    const response = result as unknown as ApiResponse
    
    if (response && (response.code === 0 || response.code === 200) && response.data) {
      // 将获取到的用户数据填充到userData对象中
      Object.assign(userData, response.data)
    } else {
      showToast({
        type: 'fail',
        message: response?.msg || t('userprofile_updateFail'),
      })
    }
  } catch (error: any) {
    console.error('err:', error)
    showToast({
      type: 'fail',
      message: error?.message || t('userprofile_updateFail'),
    })
  } finally {
    isLoading.value = false
  }
}

// 页面加载获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="less" scoped>
.user-profile {
  min-height: 100vh;
  padding: 20px;
  background: url('@/assets/images/user/Topbg.png') no-repeat center center;
  background-size: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-content {
  width: 100%;
  max-width: 650px;
  background-color: rgba(246, 224, 202, 0.1);
  border-radius: 12px;
  padding: 20px;
  position: relative;
  margin-top: 20px;
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  padding-top: 10px;
}

.logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid rgba(246, 224, 202, 0.5);
}

.info-table {
  width: 100%;
}

.info-row {
  display: flex;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 15px 0;
}

.info-label {
  width: 40%;
  color: rgba(255, 255, 255, 0.6);
  text-align: right;
  padding-right: 20px;
  font-size: 14px;
}

.info-value {
  width: 60%;
  color: #f6e0ca;
  font-size: 14px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.edit-icon {
  margin-left: 5px;
  font-size: 16px;
}

.link {
  color: #d4a85b;
  cursor: pointer;
}

.popup-content {
  padding: 20px;
}

.popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.nickname-input {
  margin-bottom: 10px;
  :deep(.van-field__control) {
    font-size: 18px;
    width: 100%;
    border: 1px solid #a9836b;
    border-radius: 4px;
    height: 40px;
    line-height: 40px;
  }
  
  :deep(.van-field__word-limit) {
    color: #666;
    margin-top: 4px;
  }
}

.popup-buttons {
  margin-top: 20px;
}

.confirm-button {
  height: 44px;
  background: linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf), linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border: none;
  
  :deep(.van-button__content) {
    color: #0c1f26;
    font-weight: 600;
    font-size: 16px;
  }
  
  &:active {
    opacity: 0.9;
  }
}
</style>
